package com.ruoyi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.domain.Article;
import com.ruoyi.domain.ConlumnMenu;
import com.ruoyi.domain.TextRead;
import com.ruoyi.domain.TextReadDto;
import com.ruoyi.service.TextReadService;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

@RestController
@RequestMapping("/textRead/textRead")
public class TextReadController extends BaseController {
    @Autowired
    private TextReadService textReadService;
    @Autowired
    private FileStorageService fileStorageService;//注入实列

    @Anonymous
    @GetMapping("/list")
    public AjaxResult list(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        // 启用分页
        PageHelper.startPage(pageNum, pageSize);
        LambdaQueryWrapper<TextRead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(TextRead::getId);
        List<TextRead> list = textReadService.list(queryWrapper);
        PageInfo<TextRead> pageInfo = new PageInfo<>(list);
        return AjaxResult.success(pageInfo);
    }

    @Anonymous
    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable("id") Long id) {
        TextRead textRead = textReadService.getById(id);
        if (textRead == null) {
            return AjaxResult.error("文章不存在");
        }
        return AjaxResult.success(textRead);
    }

    @PutMapping("/update")
    public AjaxResult update(@RequestBody TextRead textRead) {
        return AjaxResult.success(textReadService.updateById(textRead));
    }

    @PostMapping("/add")
    public AjaxResult add(@RequestBody TextRead textRead) {
        textRead.setPublishTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
        if(textReadService.save(textRead)){
            return AjaxResult.success(textRead.getId());
        }
        return AjaxResult.error("添加失败");
    }

    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Integer id) {
        return AjaxResult.success(textReadService.removeById(id));
    }

    @Anonymous
    @PostMapping("/getList")
    public AjaxResult getList(@RequestBody TextReadDto textReadDto) {
        LambdaQueryWrapper<TextRead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(textReadDto.getName()!=null,TextRead::getName,textReadDto.getName());
        queryWrapper.like(textReadDto.getContent()!=null,TextRead::getContent,textReadDto.getContent());
        queryWrapper.orderByDesc(TextRead::getId);
        queryWrapper.between(textReadDto.getStartTime()!=null && textReadDto.getEndTime()!=null,TextRead::getPublishTime,textReadDto.getStartTime(),textReadDto.getEndTime());
        return AjaxResult.success(textReadService.list(queryWrapper));
    }

    /**
     * 分页查询
     */
    @Anonymous
    @GetMapping("/getListPage")
    public AjaxResult getListByColumnId(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        // 启用分页
        PageHelper.startPage(pageNum, pageSize);
        // 查询数据列表
        List<TextRead> textReadList = textReadService.list();
        // 用PageInfo对结果进行包装
        PageInfo<TextRead> pageInfo = new PageInfo<>(textReadList);
        // 返回分页结果，包含total等信息
        return success(pageInfo);
    }
    /**
     * 封面路径
     */
    @Anonymous
    @PostMapping("/filePathImg1/{id}")
    public AjaxResult uploadFile(@PathVariable int id, @RequestParam MultipartFile file) throws Exception {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件为空");
            }

            // 获取当前日期用于文件路径
            String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

            // 构建OSS保存文件路径，使用配置的基础路径
            String objectName = "textRead/images/" + datePath + "/" + file.getOriginalFilename();

            // 上传图片到OSS，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(file)
                    .setPlatform("aliyun-oss-1") // 明确指定使用阿里云OSS平台
                    .setPath(objectName)
                    .upload();

            // 检查文件是否成功上传到OSS
            if (fileInfo == null || fileInfo.getUrl() == null) {
                return AjaxResult.error("文件上传失败");
            }

            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getFilename());
            ajax.put("newFileName", fileInfo.getUrl());
            ajax.put("originalFilename", file.getOriginalFilename());

            // 更新栏目菜单的图片路径
            TextRead byId = textReadService.getById(id);
            if (byId == null){
                return AjaxResult.error("栏目不存在");
            }
            byId.setCoverPath(fileInfo.getUrl());
            // 更新数据库记录
            boolean updateResult = textReadService.updateById(byId);
            if (!updateResult) {
                return AjaxResult.error("图片路径保存失败");
            }

            log.info("栏目图片上传成功，路径：" + fileInfo.getUrl());
            return ajax;

        } catch (Exception e) {
            log.error("栏目图片上传异常", e);
            return AjaxResult.error("上传失败: " + e.getMessage());
        }
    }
    /**
     * 文章内容图片上传
     */
    @Anonymous
    @PostMapping("/contentImage")
    public AjaxResult uploadContentImage(@RequestParam("file") MultipartFile file) throws Exception {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件为空");
            }

            // 获取 base-path
            String basePath = "textRead/contentImage/";

            // 指定oss保存文件路径
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + file.getOriginalFilename();
            // 上传图片，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(file).setPath(objectName).upload();

            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getUrl());
            ajax.put("newFileName", fileInfo.getUrl());
            ajax.put("originalFilename", file.getOriginalFilename());

            return ajax;

        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
